package thread.JUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class SharedResource {
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private int value;

    public void produce(int newValue) {
        lock.lock();
        try {
            value = newValue;
            System.out.println("Producing: " + value);
            condition.signal(); // 唤醒等待的线程
        } finally {
            lock.unlock();
        }
    }

    public int consume() {
        lock.lock();
        try {
            while (value == 0) {
                try {
                    condition.await(); // 等待，直到有数据被生产
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            int consumedValue = value;
            value = 0;
            System.out.println("Consuming: " + consumedValue);
            return consumedValue;
        } finally {
            lock.unlock();
        }
    }
}

public class Demo2 {
        public static void main(String[] args) {
            SharedResource sharedResource = new SharedResource();

            // 生产者线程
            Thread producerThread = new Thread(() -> {
                sharedResource.produce(42);
            });

            // 消费者线程
            Thread consumerThread = new Thread(() -> {
                int value = sharedResource.consume();
            });

            producerThread.start();
            consumerThread.start();
        }
    }

